using rsync;

namespace rsync
{
    internal class TimeSync
    {
        public const int InitialFrame = 0;
        public const int MaxRollbackFrames = 8;
        public const int MinFrameAdvantage = 2;
        public const int FrameAdvantageLimit = 4;
        public int SyncFrame;
        public int LocalFrame;
        public int RemoteFrame;
        public int RemoteFrameAdvantage;
        public int LocalFrameAdvantage;

        public TimeSync()
        {
            SyncFrame = InitialFrame;
            LocalFrame = InitialFrame;
            RemoteFrame = InitialFrame;
            RemoteFrameAdvantage = InitialFrame;
            LocalFrameAdvantage = 0;
        }

        public bool IsTimeSynced(Device[] devices)
        {
            int minRemoteFrame = int.MaxValue;
            int maxRemoteFrameAdvantage = int.MinValue;

            foreach (var device in devices)
            {
                if (device.Type == Device.DeviceType.Remote)
                {
                    // 查找最小远程帧
                    if (device.RemoteFrame < minRemoteFrame)
                    {
                        minRemoteFrame = device.RemoteFrame;
                    }
                    // 找到最大帧优势
                    if (device.RemoteFrameAdvantage > maxRemoteFrameAdvantage)
                    {
                        maxRemoteFrameAdvantage = device.RemoteFrameAdvantage;
                    }
                }
            }
            // 设置变量
            RemoteFrame = minRemoteFrame;
            RemoteFrameAdvantage = maxRemoteFrameAdvantage;
            // 客户机比远程客户机报告的最后一个帧提前了多远
            LocalFrameAdvantage = LocalFrame - RemoteFrame;
            int frameAdvDiff = LocalFrameAdvantage - RemoteFrameAdvantage;
            //只允许本地客户端比远程客户端领先这么远。
            return LocalFrameAdvantage < MaxRollbackFrames && frameAdvDiff <= FrameAdvantageLimit;
        }

        public bool ShouldRollback()
        {
            //如果在前一个同步帧之后没有需要同步的帧，则无需回滚。
            return LocalFrame > SyncFrame && RemoteFrame > SyncFrame;
        }
    }
}
